/****************
 *@description: 礼物收益账户详情  myPocket/userBalance/accountDetail
 *@author: Xhd
 *@API: 方子奥
 *@date: 2023-11-30 18:45:16
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from 'react';
import { Switch, InputNumber, Modal, Form, Row, Col, Space, Button, Input, Checkbox, Select, message } from "antd";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import ThePagination from "@/components/ThePagination";
import GoBack from '@/components/TheGoBack'
import { apiImMemberFreezingOrThawingLow, apiImMemberFreezingAccountStatus, apiImMemberFreezing, apiImMemberFreezingFlowingWater } from '@/request/petCoins'

export default class EventTracking extends Component {
  constructor() {
    super()
    this.FormRef = React.createRef();
    this.FeatureFormRef = React.createRef();
    this.state = {
      frozenVisible: false,
      title: "",
      amount: "",
      FeatureVisible: false,
      RecordsVisible: false,
      amountTitle: '',
      memberWalletStatusArr: { N: [], C: ["C"], T: ["T"], A: ["C", "T"] },
      recordsColumns: [
        {
          title: "冻结类型",
          key: "freezeType",
          dataIndex: "freezeType",
          render: (text, render) => {
            let txt = ''
            switch (text) {
              case 0:
                txt = '解冻'
                break;
              case 1:
                txt = '冻结'
                break;
              default:
                break;
            }
            return txt;
          }

        },
        {
          title: "类型",
          key: "operationType",
          dataIndex: "operationType",
          render: (text, render) => {
            const arr = {
              0: "人工操作",
            }
            return arr[text]
          }

        },
        {
          title: "金额",
          key: "amount",
          dataIndex: "amount",
          render: text => text && <React.$price price={text} />,
        },
        {
          title: "冻结备注",
          key: "txt",
          dataIndex: "txt",
        },
        {
          title: "操作时间",
          key: "createTime",
          dataIndex: "createTime",
        },
      ],

      columns1: [
        {
          title: "会员ID",
          key: "memberId",
          dataIndex: "memberId",
        },
        {
          title: "用户昵称",
          dataIndex: "nickName",
          key: "nickName",
        },
        // {
        //   title: "实名姓名",
        //   key: "name",
        //   dataIndex: 'name'
        // },
        {
          title: "会员手机号",
          key: "memberMobile",
          dataIndex: 'memberMobile',
          render: (text) => {
            var reg = /^(\d{3})\d{4}(\d{4})$/;
            var memberMobile = text.toString().replace(reg, '$1****$2');
            return memberMobile;
          }
        },
        {
          title: "会员状态",
          key: "memberStatus",
          dataIndex: 'memberStatus',
          render: (text, _) => {
            return { "Y": "正常", "N": "冻结" }[text]
          }
        },
        {
          title: "账户状态",
          key: "accountStatusContent",
          dataIndex: 'accountStatusContent',
          // render: (text, render) => {
          //   let txt = ''
          //   switch (text) {
          //     case 0:
          //       txt = '正常'
          //       break;
          //     case 1:
          //       txt = '封禁'
          //       break;
          //     default:
          //       break;
          //   }
          //   return txt;
          // }
        },

      ],
      info: "",
      columns2: [
        {
          title: "收益账户金额",
          key: "currentIncome",
          dataIndex: "currentIncome",
          render: text => text && <React.$price price={text} />,
        },
        {
          title: "冻结收益",
          dataIndex: "freezeEarnings",
          key: "freezeEarnings",
          render: (text, record) => {
            return <TheButton onClick={() => this.showFreezeEarnings(record.memberId)}><React.$price price={text} /></TheButton>
          }
        },
        {
          title: "可提现收益 ",
          key: "withdrawableIncome",
          dataIndex: 'withdrawableIncome',
          render: text => text && <React.$price price={text} />,
        },
        {
          title: "查看详情",
          key: "activityStatus",
          dataIndex: 'activityStatus',
          render: (text, render) => {
            return (
              <div>
                <TheButton onClick={() => this.showRecordsVisible(render.memberId)}>查看资产明细</TheButton>
              </div>
            );
          },
        },
      ],
      dataSource: [],
      type: "",
      dataSourceRecords: [],
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
      coinAccountStatus: 0,
      freezeEarnings: 0,
      memberWalletStatus: [],
      total: 0,

    }
  }
  componentDidMount() {
    this.getData()
  }

  // 获取表格数据
  getData = async () => {
    const { id } = this.props.match.params
    let res = await apiImMemberFreezingOrThawingLow({ memberId: id })
    if (res.code === 0 && res.data) {
      this.setState({
        dataSource: [res.data],
        coinAccountStatus: res.data.accountStatus,
        freezeEarnings: res.data.freezeEarnings,
        info: res.data.nickName + "(" + res.data.memberMobile + ")"
      },)
    }
  };
  // 取消
  handleCancel = () => {
    this.FormRef.current.resetFields()
    this.setState({
      frozenVisible: false,
    })
  };

  handleFeatureCancel = () => {
    this.FeatureFormRef.current.resetFields()
    this.setState({
      FeatureVisible: false,
    })
  };
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    },()=>{
      this.showFreezeEarnings()
    })
  }
  CheckboxChange = (params) => {
    this.setState({
      memberWalletStatus: params
    })
  }
  // 冻结解冻记录
  showFreezeEarnings = async (memberId) => {
    const { pageNo, pageSize} = this.state.pageData
    let res = await apiImMemberFreezingFlowingWater({memberId, pageNo, pageSize})
    if(res.code === 0 && res.data) {
      this.setState({
        dataSourceRecords: res.data,
        total: res.data.totalCount
      })
    }
    this.setState({
      RecordsVisible: true
    })
  }
  // 查看资产明细
  showRecordsVisible = async (memberId) => {
    this.props.history.push(`/myPocket/userBalance/detail/${memberId}`);
  }

  showModel = async (type) => {
    const { id } = this.props.match.params
    if (type === 1) {
      React.$confirm({
        title: "封禁账户",
        content: "封禁账户后，用户可以正常收益，但是不能提现",
        onOk: async () => {
          let res = await apiImMemberFreezingAccountStatus({ memberId: id, accountStatus: 1 })
          if (res.code === 0 && res.data) {
            React.$message({
              type: "success",
              content: "账户已封禁"
            })
          }
          this.getData()
        }
      })
    } else {
      let res = await apiImMemberFreezingAccountStatus({ memberId: id, accountStatus: 0 })
      if (res.code === 0 && res.data) {
        React.$message({
          type: "success",
          content: "账户已解封"
        })
      }
    }
    this.getData()
  }

  showFrozenVisible = (type) => {
    const { dataSource } = this.state
    let title = type === 0 ? "冻结金额" : "解冻金额"
    let amountTitle = type === 0 ? "可用收益" : "冻结收益"
    let amount = type === 0 ? dataSource[0].withdrawableIncome : dataSource[0].freezeEarnings
    this.setState({
      frozenVisible: true,
      title,
      amountTitle,
      amount,
      type
    })
  }

  showFeature = async () => {
    this.setState({
      FeatureVisible: true
    })
  }

  handleFinish = async (values) => {
    const { id } = this.props.match.params
    const { type } = this.state
    values.amount = values.amount *100
    let freezeType = ""
    if(type === 0) {
      freezeType = 1
    }else {
      freezeType = 0
    }
    let res = await apiImMemberFreezing({memberId: id, freezeType, ...values })
    if(res.code === 0) {
      React.$message({
        type: "success",
        content: type === 0 ? "冻结成功" : "解冻成功"
      })
      this.setState({frozenVisible: false,})
      this.getData()
    }
  }
  render() {
    const { coinAccountStatus, freezeEarnings, info, memberWalletStatus, recordsColumns, amountTitle, pageData: { pageNo, pageSize }, pageData, total, dataSourceRecords, frozenVisible, RecordsVisible, FeatureVisible, amount, title, columns1, dataSource, columns2 } = this.state
    return (
      <div className="p-layout-box">
        <GoBack history={this.props.history} title="" />

        <div style={{ fontWeight: 'bold' }}>会员信息</div>
        <div className="p-layout-content-pagination">
          <TheTable
            columns={columns1}
            dataSource={dataSource}
          />
        </div>
        <div style={{ fontWeight: 'bold' }}>账户信息</div>
        <div className="p-layout-content-pagination">
          <TheTable
            columns={columns2}
            dataSource={dataSource}
          />
        </div>
        <div style={{ textAlign: "center", transform: "translateY(-50px)" }}>
          {
            freezeEarnings > 0 && <TheButton type="default" size="middle" style={{ marginRight: '20px' }} onClick={() => this.showFrozenVisible(1)}>解冻金额</TheButton>
          }
          <TheButton type="primary" size="middle" style={{ marginRight: '20px' }} onClick={() => this.showFrozenVisible(0)}>冻结金额</TheButton>
          {/*{*/}
          {/*  (coinAccountStatus === 0) ? <TheButton type="primary" size="middle" style={{ marginRight: '20px' }} onClick={() => this.showModel(1)}>封禁账户</TheButton>*/}
          {/*    : <TheButton type="primary" size="middle" style={{ marginRight: '20px' }} onClick={() => this.showModel(0)}>解封账户</TheButton>*/}
          {/*}*/}
        </div>
        <Modal title={'功能禁用'} visible={FeatureVisible} width="40%"
          onCancel={() => this.handleFeatureCancel()}
          footer={null}
        >
          <Form
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 14,
            }}
            ref={this.FeatureFormRef}
            onFinish={(values) => this.handleFinishOnly(values)}
          >
            <Form.Item
              label="禁用功能"
            // name="memberWalletStatus"
            >
              <Checkbox.Group
                options={[{
                  label: '提现',
                  value: 'T',
                },
                {
                  label: '充值',
                  value: 'C',
                }]}
                defaultValue={memberWalletStatus}
                onChange={this.CheckboxChange}
              />
            </Form.Item>
            <Form.Item wrapperCol={{
              offset: 12,
              span: 16,
            }}>
              <Space size="small" style={{ marginLeft: 10 }}>
                <Button type="default" onClick={() => this.handleFeatureCancel()}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal >
        <Modal title={'冻结解冻记录'} visible={RecordsVisible} width="70%" footer={null}
          onCancel={() => this.setState({ RecordsVisible: false, pageData: { pageNo: 1, pageSize: 10 }, })}
        >
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={recordsColumns}
            dataSource={dataSourceRecords}
            pageData={pageData}
          />
          <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </Modal >

        <Modal title={title} visible={frozenVisible} width="30%"
          onCancel={() => this.handleCancel()}
          footer={null}
          destroyOnClose
        >
          <Form
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 14,
            }}
            ref={this.FormRef}
            onFinish={(values) => this.handleFinish(values)}
          >
            <Form.Item
              label="会员"
            >
              {info}
            </Form.Item>
            <Form.Item
              label={title}
              name="amount"
              rules={[
                {
                  required: true,
                  message: '请输入' + title,
                },
                {
                  pattern: /^\d+(\.\d{0,})$|(^[0-9]\d*$)/,
                  message: '请输入有效数字',
                },
              ]}
            >
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <InputNumber placeholder={'请输入' + title}  />
                <div style={{ whiteSpace: 'nowrap', marginLeft: "20px" }}>{amountTitle + ': '}<React.$price price={amount} /></div>
              </div>
            </Form.Item>
            <Form.Item
              label="备注"
              name="txt"
              rules={[
                {
                  required: true,
                  message: '请输入备注',
                },
              ]}
            >
              <Input placeholder='请输入备注，200字以内' maxLength={200} />
            </Form.Item>
            <Form.Item wrapperCol={{
              offset: 12,
              span: 16,
            }}>
              <Space size="small" style={{ marginLeft: 10 }}>
                <Button type="default" onClick={() => this.handleCancel()}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </div >
    );
  }
}
